<template>
    <div style="" class="wed-con w-100">
        <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" class="wed-bottom" />
        <Editor v-model="vModelData" :defaultConfig="editorConfig" @onChange="onChange" @onCreated="onEditorCreated" :style="{ height: height + 'px', overflowY: 'hidden' }" v-bind="$attrs" />
    </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css";
import { onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import toolbarConfigs from "@/components/WEditor/ToolbarConfig";
import editorConfigs from "@/components/WEditor/EditorConfig";

//工具栏配置项
const toolbarConfig: Partial<IToolbarConfig> = toolbarConfigs;

//编辑器配置项
const editorConfig: Partial<IEditorConfig> = editorConfigs;

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

//v-model相关
const props = defineProps({
    modelValue: String,

    height: {
        type: [String, Number],
        default: "300",
    },
});

//下拉列表v-model绑定的值
const vModelData = ref();

//编辑器创建时触发
onMounted(() => {
    nextTick(() => {
        vModelData.value = props.modelValue;
    });
});

//监听数据变化
watch(
    () => props.modelValue,
    (newVal, oldVal) => {
        vModelData.value = newVal;
    }
);

//editor内容改变事件
const onChange = () => {
    emit("update:modelValue", editorRef.value.getHtml());
};

//组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    let editor = editorRef.value;

    if (Gx.IsEmpty(editor)) {
        return;
    }

    editor.destroy();
});

//组件在创建后
const onEditorCreated = (editor: IDomEditor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};

const emit = defineEmits(["update:modelValue"]);
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.wed-con {
    border: 1px solid $global-border-color;
}
.wed-bottom {
    border-bottom: 1px solid $global-border-color;
}
</style>
